package com.sinothk.gpserver.modules.comm.files.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sinothk.gpserver.modules.comm.files.entity.FileEntity;
import com.sinothk.gpserver.modules.comm.files.mapper.FileMapper;
import com.sinothk.gpserver.modules.comm.files.service.FileService;
import com.sinothk.server.support.annotation.callback.BizException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 编写 Liang Y.T.
 * 时间 2021/11/19 0:26
 */
@Service
public class FileServiceImpl extends ServiceImpl<FileMapper, FileEntity> implements FileService {

    @Value(value = "${sinothk.filePath}")
    private String filePath;

    @Override
    public FileEntity uploadFile(String bizType, MultipartFile mf) {

        if (StringUtils.isEmpty(bizType)) throw new BizException("biz业务目录不能为空");
        String fileName = null;

        String dayStr = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String subPath = bizType + File.separator + dayStr;
        String allPath = filePath + subPath;
        File file = new File(allPath);

        if (!file.exists()) {
            file.mkdirs();// 创建文件根目录
        }
        String orgName = mf.getOriginalFilename();// 获取文件名
        fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));

        subPath = subPath + File.separator + fileName;
        String savePath = filePath + subPath;

        File saveFile = new File(savePath);

        try {
            FileCopyUtils.copy(mf.getBytes(), saveFile);
        } catch (Exception e) {
            throw new BizException(e.getMessage());
        }

        FileEntity fileEntity = new FileEntity();
        fileEntity.setFilePath(subPath);
        fileEntity.setFileUrl(subPath.replace("\\", "/"));
        this.save(fileEntity);
        return fileEntity;
    }
}
